package com.pt25.base.exception;


import com.pt25.base.res.ResBody;
import com.pt25.base.res.ResCode;
import lombok.extern.log4j.Log4j2;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 异常处理器（全局拦截异常处理）
 *
 * @ControllerAdvice 这是一个增强的 Controller。使用这个 Controller ，可以实现三个方面的功能：
 * <p>
 * 全局异常处理
 * 全局数据绑定
 * 全局数据预处理
 */
@Log4j2
@ControllerAdvice
@ResponseBody
public class ExceptionHandler {


    @org.springframework.web.bind.annotation.ExceptionHandler(BizException.class)
    @ResponseBody
    public ResBody handleCustomException(BizException e) {
        log.error("系统错误日志：{}", e.getMsg());
        return ResBody.builder().code(e.getCode()).msg(e.getMsg()).build();
    }

    /**
     * HibernateValidator验证消息返回（请求参数验证）异常处理
     */
    @org.springframework.web.bind.annotation.ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseBody
    public ResBody handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        printLog(e);
        BindingResult result = e.getBindingResult();
        StringBuilder errorMsg = new StringBuilder();
        for (ObjectError error : result.getAllErrors()) {
            errorMsg.append(error.getDefaultMessage()).append(",");
        }
        return ResBody.builder().code(ResCode.FAIL.getCode()).msg(errorMsg.toString()).build();
    }


    @org.springframework.web.bind.annotation.ExceptionHandler(Exception.class)
    @ResponseBody
    public ResBody handleException(Exception e) {
        printLog(e);
        return ResBody.builder().code(ResCode.FAIL.getCode()).msg(e.getMessage()).build();
    }

    private void printLog(Exception e) {
        log.error("错误日志:", e);
    }
}
